/**
 * 火车票封装的方法
 * @author hongwei 2018-08-03
 */
// +----------------------------------------------------------------------
// | 基本知识
// | isApply=0      0关闭，1开启
// | orderType=0    0因私，1因公
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 目录
// | step01:初始化方法                        _init

// | step02:获取出差申请单列表                applyList（放在前边先加载，后边判断隐藏）
// | step03:获取出差申请单列表                applyStatus
// | step04:页面初始化操作                    initPage
// | step05:因公因私点击判断                  orderTypeClick
// | step06:选择申请单事件监听                selectApply
// | step07:监听城市                          cityListen
// | step08:点击查询                          trainSearch

// | $api.rmStorage('travel_people_id_array');          //删除人员的id_array
// | $api.setStorage('travel_people_id_array', user_id); // 存储：用户对象，例：[1]
// | $api.setStorage('order_type', that.params.order_type);    //0因公1因私
// | $api.setStorage('order_self', that.params.order_self);    //2为自己3为他人
// | $api.setStorage('start_date', start_date_true);    //开始时间
// | $api.setStorage('isApply', isApply);               //开启关闭申请单
// +----------------------------------------------------------------------


(function (window) {
    'use strict';

    let trainSearch = function(params) {
        this.extend(this.params, params);
        this._init();
    };
    trainSearch.prototype = {
        //参数
        params : {
            'order_type'        : '1'  //0因私，1因公，初始为因私(edit zhugeng 2018-09-14 隐藏因私，初始化因公，后面加上因私，改为0)
            ,'order_self'       : '1'  //2为自己，3为他人,初始为一个没有的值，例1
            ,'select_number'    : ''   //选择的申请单号
            ,'isApply'          : ''   //是否开启申请单，0关闭，1开启
            ,'dataInter'        : ''   //存入的申请单数据
        }

        //step01:初始化操作
        ,_init: function() {
            let that = this;

            if(typeof(api) === 'undefined'){
                console.log('该插件只能在apicloud下运行');
            }else{
                //that.formVal();             //表单测试
                that.applyStatus();         //step03:是否开启申请单
                that.initPage();            //step04:页面初始化操作
                that.orderTypeClick();      //step05:因公因私点击判断 - 有申请单的条件下
                that.selectApply();         //step06:选择申请单事件监听 - 有申请单的条件下
                that.cityListen();          //step07:监听城市
                // that.trainSearchClick();  //step08:点击查询
            }
        }
        //初始化测试表单数据
        ,formVal : function(){
            $('#trainStart').val('太原');
            $('#trainEnd').val('榆次');
        }
        //step02:获取出差申请单列表
        ,applyList: function () {
            let that = this;
            //获取出差申请单列表
            let param = {};
            param.url = Config.common.getApplyListOfCurrent;
            param.data = {};
            let html = '';
            ajax(param, function (ret) {
                if (ret.code === 1) {
                    that.params.dataInter = ret.data;
                    //step02-1：追加数据
                    $.each(ret.data, function (index, value) {
                        html += '<option value="' + index + '">' + value.travel_application_number + '</option>';
                    });
                    $("#travel_id").append(html);
                    //step02-2:初始化select2
                    let areaObj = $("#travel_id").select2();
                    areaObj.val(-1).trigger("change");
                    areaObj.change();
                } else {
                    $alert(ret.msg);
                }
            });
        }

        //step03:获取出差申请单列表,isApply=0未开启，1开启
        ,applyStatus: function () {
            let that = this;
            let params = {};
            params.url = Config.common.getCompanyInfo;
            params.data = {};
            ajax(params, function (res) {
                //res = {apply_order: 1, expense_order: 1}
                that.params.isApply = res.apply_order;
                $api.setStorage('isApply', that.params.isApply);    //开启关闭申请单
                that.applyList();           //step02:获取出差申请单列表
                //edit    zhugeng   2018-09-14(加上因私去掉这块)
                if ($api.getStorage('isApply') == 1) {
                    $('.orderN').removeClass('aui-hide');  //出行具体信息
                } else {
                    $('.orderN').addClass('aui-hide');      //出行具体信息
                }
            })
        }

        //step04:页面初始化操作
        ,initPage: function () {
            let that = this;
            //初始化数据
            //$('#trainStart').val('');
            //$('#trainEnd').val('');

            //step03-1:删除人员的id_array
            $api.rmStorage('travel_people_id_array');
            //step03-2:存储和删除storage
            $api.setStorage('order_type', that.params.order_type); //因公因私
            $api.setStorage('order_self', that.params.order_self); //为自己为他人
            //step03-3:时间选择
            //edit  zhugeng 2018-09-14
            $('.date-time').hotelDate({
                date: 2,is_train:1
            }, function(ret) {
                // console.log(ret);
                /*判断是否为今天*/
                $('.one_way_time span').html(ret.train_month + '月' + ret.train_day + '日');
                if (getBeforeDate(0) == ret.enterTime.replace(/\//g, '-')) {
                    $('.one_way_time e').empty().append('<e style=""> 今天</e>');
                } else if (getBeforeDate(-1) == ret.enterTime.replace(/\//g, '-')) {
                    $('.one_way_time e').empty().append('<e style=""> 明天</e>');
                } else if (getBeforeDate(-2) == ret.enterTime.replace(/\//g, '-')) {
                    $('.one_way_time e').empty().append('<e style=""> 后天</e>');
                } else {
                    $('.one_way_time e').empty().append('<e style=""> </e>')
                }
                //            将时间存入sessionStorage
                let start_date_true = ret.enterTime.replace(/\//g, "-");  //时间
                $('#realyDate').val(start_date_true);
                $api.setStorage('start_date', ret.enterTime);

            });
            //注释    zhugeng  2018-09-14
            // $('.date-time').each(function() {
            //     $(this).hotelDate({date:2,is_train:1},function(ret){
            //         $("#my-startDate").val(ret.train_month+"月"+ret.train_day+"日");
            //         let train_date_temp = ret.enterTime;
            //         let start_date_true = train_date_temp.replace(/\//g, "-");  //时间
            //         $('#realyDate').val(start_date_true);
            //         $api.setStorage('start_date', start_date_true); //开始时间
            //     });
            // });
            //step03-4:地点切换
            $('#commutation').click(function(){
                let train_s  = $('#trainStart').val();
                let train_e  = $('#trainEnd').val();
                $('#trainStart').val(train_e);
                $('#trainEnd').val(train_s);
            });
        }

        //step05:因公因私点击判断
        ,orderTypeClick: function () {
            let that = this;
            //因私因公触发事件
            $('body').on('click', '.order_radio', function(){
                that.params.order_type = $("input[name='order_type']:checked").val();
                if (that.params.order_type == 0) {
                    let date = new Date();
                    let month = date.getMonth() + 1;
                    let day = date.getDate();
                    $('.one_way_time span').html(month + '月' + day + '日');

                    $('.orderN').addClass('aui-hide');    //申请单号隐藏
                    $('.traves').addClass('aui-hide');    //出行具体信息隐藏
                    $api.setStorage('order_self', 1);
                    $api.setStorage('order_type', that.params.order_type);
                } else {
                    // $('#trainStart').val('');
                    // $('#trainEnd').val('');
                    if ($api.getStorage('isApply') == 1) {
                        $('.orderN').removeClass('aui-hide');  //出行具体信息
                    } else {
                        $('.orderN').addClass('aui-hide');      //出行具体信息
                    }
                    $api.setStorage('order_type', that.params.order_type);
                }
            });
        }

        //step06:选择申请单事件监听
        ,selectApply : function() {
            let that = this;
            //选择申请单事件监听
            let selected_staff = [];
            $("#travel_id").change(function() {
                //step01:选择申请单号与为空、隐藏判断
                // $('#trainStart').val('');
                // $('#trainEnd').val('');
                that.params.select_number = $(this).children('option:selected').text();
                if (that.params.select_number == '请选择申请单号') {
                    $('#trainStart').val('');
                    $('#trainEnd').val('');
                    $('.traves').addClass('aui-hide'); //test
                }
                //step02:对申请单号信息操作
                let dataInter = that.params.dataInter;
                if (dataInter != '') {

                    $.each(dataInter, function (index, item) {
                        if (that.params.select_number == item.travel_application_number) {
                            //step02-1：存储两个参数
                            $api.setStorage('oa_number', item.travel_application_number);    //申请单号
                            $api.setStorage('selected_staff',item.business_traveler);       //出行人员信息

                            //step02-2:根据出行人判断因公因私
                            let user_id = $api.getStorage('user_id');
                            if (item.business_traveler.length == 1 && item.business_traveler[0].user_id == user_id) {
                                //a.因公为自己
                                $api.setStorage('order_self', 2);
                                $api.setStorage('travel_people_id_array', user_id); // 存储：用户对象，例：[1]
                            } else {
                                //b.因公为他人
                                $api.setStorage('order_self', 3);
                                let travel_people_id_arrays = that.changObjkey(item.business_traveler, 'user_id');
                                let travel_people_id_array  = Object.keys(travel_people_id_arrays);
                                let travel_people_id_array_string = travel_people_id_array.join(',');
                                $api.setStorage('travel_people_id_array', travel_people_id_array_string); // 存储：用户对象，例：[1,2]
                            }

                            //step02-3:处理出差日期\出差行程
                            let start_date = item.travel_time.substr(0,4)+'-'+item.travel_time.substr(5,2)+'-'+item.travel_time.substr(8,2);
                            let citys = item.travel_site+'-'+item.travel_destination;
                            $('.start_dt').text(start_date);
                            $('.city').text(citys);
                            let travel_html = '';
                            $('.peoples').html('');

                            //step02-4:处理人员
                            //edit zhugeng 2018-09-14
                            var nameArry = [];
                            for (var k in item.business_traveler) {
                                 nameArry.push(item.business_traveler[k].user_name);
                            }
                            // $.each(item.business_traveler,function(index2,item2){
                            //     travel_html += '<div class="one_way_address" style="border-bottom:1px solid #DCDCDC;overflow:hidden;">';
                            //     travel_html += '<div class="aui-list-item-label card_side u_ticket" style="width:50%;float:left;height:2.5rem;line-height:2.5rem;color:black;">';
                            //     travel_html += '<span style="display:inline-block;text-align:center;line-height:0.8rem; border-radius:50%;width:0.8rem;height:0.8rem;background:#C5C5C5;color:white;margin-left:1rem;margin-right:1rem;font-size:0.5rem;">'+parseInt(index2+1)+'</span><span style="color:#C5C5C5;">'+item2.user_name+'</span>';
                            //     travel_html += '</div>';
                            //     travel_html += '<div class="aui-list-item-input"  style="float: right;height:2.5rem;line-height:2.5rem;color:#C5C5C5;">手机号：'+item2['mobile'];
                            //     travel_html += '</div>';
                            //     travel_html += '</div>';
                            // });
                            $('.traves').removeClass('aui-hide');
                            $('.peoples').append(nameArry.join(','));
                        }
                    });

                }
            })
        }

        //step07:监听城市
        ,cityListen: function () {
            let that = this;
            //发送监听事件
            api.addEventListener({
                name: 'cityName'
            }, function (ret, err) {
                //step1:监听到的城市
                // console.log(JSON.stringify(ret));//{"value":{"city_on":0,"cname":"成都"}}
                let city_on = ret.value.city_on;
                //step2:处理数据
                //console.log(that.params.order_type);  //因公状态
                //console.log(that.params.isApply);     //申请单状态
                if (that.params.order_type == 1 && (that.params.isApply == 1)) { //因公且有申请单
                    //判断选择的城市是否在申请单城市里
                    $.each(that.params.dataInter, function(i, value){
                        if (that.params.select_number == value.travel_application_number) {
                            if (value.travel_destination.indexOf(ret.value.cname) != -1 || value.travel_site == ret.value.cname) {
                                if (city_on == 0) {
                                    $('#trainStart').val(ret.value.cname);
                                } else {
                                    $('#trainEnd').val(ret.value.cname);
                                }
                            } else {
                                $alert('该申请单所申请的城市中并不包含当前所选城市，请重新选择');
                            }
                        }
                    });
                } else {
                    if (city_on == 0) {
                        $('#trainStart').val(ret.value.cname);
                    } else {
                        $('#trainEnd').val(ret.value.cname);
                    }
                }
            });
        }

        //step08:点击查询
        ,trainSearchClick: function () {
            let that = this;
            $api.setStorage('is', true);
            //step1:出发城市和到达城市为空判断
            let train_start = $('#trainStart').val();
            let train_end   = $('#trainEnd').val();
            //console.log(train_start);
            //console.log(train_end);
            let toast = new auiToast();
            if(train_start.length <= 0) {
                toast.fail({
                    title:"出发城市不可为空",
                    duration:2000
                });
                return false;
            }
            if(train_end.length <= 0) {
                toast.fail({
                    title:"到达城市不可为空",
                    duration:2000
                });
                return false;
            }
            //step2:开启申请单为空判断
            if (parseInt($("input[name='order_type']:checked").val()) === 1 && parseInt(that.params.isApply) === 1) {
                let travel_id = $('#travel_id').val();
                if (travel_id === '-1' || travel_id === undefined || travel_id === ''){
                    $alert('申请单号为空，请先选择申请单号再查询！');
                    return false;
                }
            }

            //step3: 申请单日期判断
            //zhugeng   2018-09-17   暂时先去掉因私，这块暂不作判断
            //step1:出行日期时间
            let applyDate = $('.start_dt').text();  //出行日期时间
            $api.setStorage('travel_time', applyDate);
            let applyTime = new Date(applyDate).getTime(); //申请出行日期时间戳
            //step2:选择日期
            let trueDate = $('#realyDate').val(); //选择日期的时间戳
            let trueTime = new Date(trueDate).getTime();
            //step3：比较
            if (applyTime > trueTime) {
                $alert('出行日期需大于等于出差申请单中的申请日期');
                return false;
            }
            // if ($('.order_radio').val() == 1 && parseInt(that.params.isApply) === 1) {
            //
            // }
            $api.setStorage('s_time', $('#realyDate').val());

            openWin('train_result', './train_result_win.html',{
                train_start : train_start,
                train_end   : train_end,
                train_date  : $('#realyDate').val(),
            });

        }

        //step09:工具-如何获取json对象中的特定值(不支持数组)
        ,getJsonValue :function (obj,name){
            let that = this;

            var result = null;
            var value  = null;
            for(var key in obj){
                value = obj[key];
                if(key == name){
                    return value;
                } else {
                    if( typeof value == "object" ){
                        result = that.getJsonValue(value,name);
                    }
                }
            }
            return result;
        }

        //改变数组的key值
        //var jsonArr = [
        //     {"id": "1", "name": "A1"},
        //     {"id": "2", "name": "A2"},
        //     {"id": "3", "name": "A3"},
        //     {"id": "4", "name": "A4"},
        //     {"id": "5", "name": "A5"}
        // ];
        //eg: changObjkey(jsonArr, 'id');
        ,changObjkey: function (data, field, unique) {
            var newArr = {};
            for (var i in data) {
                if (data[i][field]) {
                    if (unique == true) {
                        //todo 完善这里
                    } else {
                        newArr[data[i][field]] = data[i];
                    }
                }
            }
            return newArr;
        }

        //函数:扩展
        ,extend: function (a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }
    };
    window.trainSearch = trainSearch;
})(window);
